package cn.iocoder.yudao.module.iot.component;

import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.iot.dal.dataobject.scene.IotSceneDO;
import cn.iocoder.yudao.module.iot.dal.mysql.scene.IotSceneMapper;
import cn.iocoder.yudao.module.iot.service.scene.IotSceneTimerService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 场景定时任务初始化组件
 *
 * 系统启动时自动同步所有场景的定时任务
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class SceneTimerInitializer implements CommandLineRunner {

    @Resource
    private IotSceneMapper sceneMapper;

    @Resource
    private IotSceneTimerService iotSceneTimerService;

    @Override
    public void run(String... args) throws Exception {
        log.info("[SceneTimerInitializer][开始初始化场景定时任务]");
        
        try {
            // 设置默认租户ID
            TenantContextHolder.setTenantId(1L);
            
            // 第一步：清理旧的定时任务
            log.info("[SceneTimerInitializer][开始清理旧的定时任务]");
            iotSceneTimerService.cleanupOldJobs();
            
            // 第二步：获取所有启用的场景
            List<IotSceneDO> enabledScenes = sceneMapper.selectListByStatus(1);
            
            log.info("[SceneTimerInitializer][找到 {} 个启用的场景]", enabledScenes.size());
            
            int successCount = 0;
            int failCount = 0;
            
            for (IotSceneDO scene : enabledScenes) {
                try {
                    // 使用反射调用内部方法，避免清理租户上下文
                    Method syncMethod = iotSceneTimerService.getClass().getDeclaredMethod("syncSceneTimerInternal", Long.class, boolean.class);
                    syncMethod.setAccessible(true);
                    syncMethod.invoke(iotSceneTimerService, scene.getId(), false);
                    
                    successCount++;
                    log.debug("[SceneTimerInitializer][同步场景定时任务成功，场景ID: {}]", scene.getId());
                } catch (Exception e) {
                    failCount++;
                    log.error("[SceneTimerInitializer][同步场景定时任务失败，场景ID: {}]", scene.getId(), e);
                }
            }
            
            log.info("[SceneTimerInitializer][场景定时任务初始化完成，成功: {}, 失败: {}]", successCount, failCount);
            
        } catch (Exception e) {
            log.error("[SceneTimerInitializer][场景定时任务初始化失败]", e);
        } finally {
            // 清理租户上下文
            TenantContextHolder.clear();
        }
    }
} 